package net.sareweb.acab.actions.travel;

import net.sareweb.acab.components.session.AcabIdentity;
import net.sareweb.acab.entity.*;
import net.sareweb.acab.entity.manager.CommentManager;
import net.sareweb.acab.entity.manager.DialogManager;
import net.sareweb.acab.entity.manager.TravelManager;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.framework.EntityQuery;
import org.jboss.seam.log.Log;

import java.util.Arrays;
import java.util.Date;

import javax.faces.event.ActionEvent;

@Name("findTravelsBean")
public class FindTravelsBean extends EntityQuery<Travel> {
	@Logger 
	private Log log;
	@In 
    AcabIdentity identity;
	@In (create = true)
    DialogManager dialogManager;
	@In (create = true)
    TravelManager travelManager;
	@In (create = true)
    CommentManager commentManager;
	
	private static final String EJBQL = "select travel from Travel travel";

	private static final String[] RESTRICTIONS = {
			"lower(travel.name) like lower(concat(#{findTravelsBean.travel.name},'%'))",
			"travel.user.idUser = #{findTravelsBean.travel.user.idUser}",};

	private Travel travel = new Travel();
	
	//params for writing a message and create a new dialog
	private String newMessage="Interested in this travel? write a message.";
	private Integer toTravel;
	

	public FindTravelsBean() {
		setEjbql(EJBQL);
		setRestrictionExpressionStrings(Arrays.asList(RESTRICTIONS));
		setMaxResults(25);
	}
	
	
	public String writeMsgAction(){
		Dialog d = dialogManager.findByTravelOtherUser(toTravel, identity.getUser().getIdUser());
		if(d!=null){//TODO: allready exists a dialog for this travel with this user, handle it
			return "";
		}
		
		Travel t = travelManager.find(toTravel);
		
		Dialog newD = new Dialog();
		newD.setCreateDate(new Date());
		newD.setLastCommentDate(new Date());
		newD.setOtherSeenDate(new Date());
		newD.setTravel(t);
		newD.setUser(identity.getUser());
		
		dialogManager.save(newD);
		
		
		Comment newC = new Comment();
		newC.setCreateDate(new Date());
		newC.setDialog(newD);
		newC.setMsg(newMessage);
		newC.setUser(identity.getUser());
		
		commentManager.save(newC);
		
		
		return "/home.xhtml";
	}
	
	public void writeMsgActionListener (ActionEvent event){
		log.debug("sent message --> \"{0}\" to travel \"{1}\"", newMessage, toTravel);
		
	}

	public Travel getTravel() {
		if(travel.getUser()==null)travel.setUser(new User());
		return travel;
	}


	public String getNewMessage() {
		return newMessage;
	}


	public void setNewMessage(String newMessage) {
		this.newMessage = newMessage;
	}


	public Integer getToTravel() {
		return toTravel;
	}


	public void setToTravel(Integer toTravel) {
		log.debug("to travel \"{0}\"", toTravel);
		this.toTravel = toTravel;
	}
	
	
	
}
